<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use App\Models\Agent;
use App\Models\Agentlev;
use App\Models\Area;
use App\Models\Brand;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;

use Maatwebsite\Excel\Facades\Excel;
Class IndexController extends BaseController {

    public function __construct(Agentlev $agentlev , Agent $agent ,Order $order , Admin $admin , Area $area,Brand $brand)
    {
        parent::__construct();
        $this->agentlev = $agentlev;
        $this->agent = $agent;
        $this->order = $order;
        $this->admin = $admin;
        $this->area = $area;
        $this->brand = $brand;
    }

    /**
     * 获取用户登录信息
     */
    public function getAdminInfo(){
          $aid = session('token');
          $res = $this->agent->getAgentInfo($aid['admin']);
          return ajax_return($res);
    }

    // 获取层级代理信息,代理层级列表
    public function getIndex(){

         $res = $this->agentlev->getAgentList(request());
         $flag='agent_lev';
         //dd(session());
         return view("agent.index.lev_list",compact('res','flag'));
    }

    //ajax删除代理层级
    public function postDelAgentLev(){

        $res = $this->agentlev->delAgentLev(request());
        return ajax_return($res);
    }

    public function getLev(){
         $data = $this->agentlev->getAgentList(request());
         if(empty($data)){
             $res = ['status'=>0,"msg"=>"暂无数据"];
             return ajax_return($res);
         }
        $res = ['status'=>200,'msg'=>"ok",'data'=>$data];
        return ajax_return($res);
    }

    //品牌代理成员详情
    public function getAgentInfo(){


         $data = [];
         $flag = 'agent';

         $res = $this->agent->getAgentInfo(request('id'));

        //下级代理人数
         $res['data']['last_num'] = count($this->agent->getList(array('pid'=>request('id'))));
         $order = $this->order->getAgentOrderList(request());
         $num = $this->order->getCount(['aid'=>request('id')]);
         //dd($num);
         $data['agent'] = $res;
         $data['order'] = $order;



         //dd($data);
        return view('agent.index.agent_info',compact('data','flag','num'));
         //return ajax_return($data);
    }

    /***生成excel**/
    public function getExcel()
    {
        //dd($_GET);
        $where['aid'] = request('id');
        $start = date("Y-m-d", strtotime(request('starttime')));
        $end = date("Y-m-d", strtotime(request('endtime')));
        $start1 = $start;
        $end1 = $end;
        if ($start > $end) {
            $start1 = $end;
            $end1 = $start;
        }
        //如果开始时间和结束时间相等
        if (request('starttime') && request('endtime')&&(request('starttime')==request('endtime'))) {
            $selectTime = Carbon::parse($start1);  //选中当天的0点0分
            Carbon::setTestNow($selectTime);     //设置选中事件为当前时间
            $selectTomorrow = new Carbon('tomorrow');   //选中后一天的0点0分
            $where['created_at'] = ['glt', [['>', $selectTime], ['<', $selectTomorrow]]];
        }elseif(request('starttime') && request('endtime')){
            $selectTime = Carbon::parse($end1);
            Carbon::setTestNow($selectTime);
            $selectTomorrow = new Carbon('tomorrow');
            $where['created_at'] = ['glt', [['>', $start1], ['<', $selectTomorrow]]];
        }else{

        }

        $fields = 'goods_name,goods_num,created_at,status';

        if(request('num1')!='null'&&request('num2')!='null'){
            $num1 = request('num1');
            $num2 = request('num2');
            $num2 = $num2 - $num1;
        }
        //$order = $this->order->getExcel($where,$fields,['created_at'=>'desc'],'')->offset($num1)->limit($num2)->toSql();
        $order = $this->order->getExcel($where,$fields,['created_at'=>'desc'])->skip($num1)->take($num2+1)->get()->toArray();
        $agent = $this->agent->getOne(['id'=>request('id')]);
        $agent_name = $agent['agent_name'];

        foreach ($order as $k1=>$v1)
        {

            foreach ($v1 as $k2=>$v2){

                if($v1['status']==0){
                    $order[$k1]['msg'] = '未发货';
                }
                if($v1['status']==1){
                    $order[$k1]['msg'] = '已发货,待确认';
                }
                if($v1['status']==2){
                    $order[$k1]['msg'] = '已确认收货';
                }

            }


        }

        $export = [];
        foreach ($order as $k=>$v)
        {
            $export[] = [
                '产品名称'=>$v['goods_name'],
                '产品数量'=>$v['goods_num'],
                '下单时间'=>$v['created_at'],
                '订单状态'=>$v['msg'],
            ];
        }


        $tab_name = '代理'.$agent_name.'商品销售情况';
        Excel::create($tab_name, function($excel) use ($export) {

            $excel->sheet('export', function($sheet) use ($export) {
                $sheet->fromArray($export);
            });

        })->export('xls');



    }


    public function getLastAgent(){
         $where['pid'] = request('id');
         if(request('lev')){
               $where['lev'] = request('lev');
         }
         if(request('mobile')){
                $where['mobile'] = request('mobile');
         }
         $order['id'] = "desc";
         $rows = $this->agent->getList($where,"*",$order,10);
         if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'],request('page',1),10);
         }
         return ajax_return($rows);
    }


    //代理成员管理+搜索
    public function getAgent(){
        $res = $this->agent->getAgentList(request());
        $flag='agent';
        $levinfo = $this->agentlev->getAgentList(request());
        return view("agent.index.agent_list",compact('res','flag','levinfo'));
    }


    //ajax删除代理成员
    public function getAgentDel()
    {
        $res = $this->agent->deleteOneAgent(request());
        return ajax_return($res);

    }

    //代理成员审核管理
    public function postVerify()
    {
//        $res = $this->brand->verify(request());
//        return ajax_return($res);

        $res = $this->agent->verify(request());
        return ajax_return($res);
    }

    public function postAgentUpload(){
        $res = $this->agent->AgentUpload(request());
        return ajax_return($res);
    }

    // 添加代理成员
    public function postAddAgent(){
         $res = $this->agent->addAgent(request());
         return ajax_return($res);
    }

    // 编辑代理层级
    public function getEdit(){

          $res = $this->agentlev->getEdit(request());
         return ajax_return($res);

    }

    /*
     * 添加层级信息
     * */
    public function postAddAgentLev(){

        $res = $this->agentlev->addAgentLev(request());
        //dd($res);

        if($res['status']==200){
            return redirect()->back()->with('message', $res['msg'])->withInput();

        }else{
            return redirect()->back()->with('message', $res['msg'])->withInput();

        }


    }

    /**
     * 品牌代理书
     * @return
     */
    public function getImageSoucer(){
         $res = $this->brand->getImageData(request());
         //$file = 'upload/agent/'.session('agentId').'.png';
        //dd($res);
         $data['proxy'] = $res['proxy'];
        //dd(123);
         $flag = 'shu';
         return view('agent.index.agent_img',compact('data','flag'));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 获取模板
     */
    public function getImageMoban()
    {

        $res = $this->admin->getImageData(request());  //获取模板
        //$file = 'upload/agent/'.session('agentId').'.png';
        //dd($res);
        $data['proxy'] = $res['proxy'];
        $flag = 'shu';
        return view('admin.index.agent_img',compact('data','flag'));

    }

    //上传模板
    public function postSaveUpload2()
    {
        $res = $this->admin->uploadImage(request());
        return $res;
    }

    /**
     * 下载图片
     */
    public function getDownImage(){
         $this->admin->getDownImage();
    }

    /**
     * 上传代理书
     */
    public function postSaveUpload(){
         $res = $this->agent->AgentUploadTo(request());
         return ajax_return($res);
    }

    public function getAddress(){
         $res = $this->area->getChild(request());
         return ajax_return($res);
    }

    /*
     * 编辑代理信息
     * */
    public function postSaveAgent(){
        $res = $this->agentlev->saveAgentLev(request());
        //dd($res);
        //return ajax_return($res);
        if($res['status']==200){

            return redirect()->back()->with('message', $res['msg'])->withInput();

        }else{

            return redirect()->back()->with('message', $res['msg'])->withInput();

        }

    }






}